<?php

namespace Common\Controller;

/**
 * 验证码控制器
 * 
 * @since 1.0 2014-6-13 by sutroon
 */
class CaptchaController extends \Think\Controller {

    /**
     * 生成验证码
     * @param string $id
     * @since 1.0 <2014-6-13> sutroon Added.
     * @since 2.0 <2015-4-15> SoChishun Refactoring function..
     * @since 2.1 <2015-4-17> SoChishun Refactoring params.
     */
    public function index($id = 'captcha') {
        $config = array(
            'length' => I('get.len', 4),
            'imageH' => I('get.h', 22),
            'fontSize' => I('get.fs', 12),
            'useCurve' => false,
            'useNoise' => false,
            'fontttf' => '1.ttf',
        );
        if (I('w')) {
            $config['imageW'] = I('w');
        }
        $this->entry($config);
    }

    /**
     * 生成验证码图片
     * @param array $config
     * @param string $id
     * @since 1.0 <2015-4-17> SoChishun Added.
     */
    public function entry($config = array(), $id = 'captcha') {
        $options = array(
            'length' => 4,
            'imageH' => 22,
            'fontSize' => 12,
            'useCurve' => false,
            'useNoise' => false,
            'fontttf' => '1.ttf',
            'codeSet' => '012345679',
        );
        $config = array_merge($options, $config);
        $verify = new \Think\Verify($config);
        $verify->entry($id);
    }

    /**
     * 检验验证码
     * @param string $code
     * @param string $id
     * @param boolean $reset 是否重置验证码
     * @return boolean
     * @since 1.0 <2014-6-13> sutroon Added.
     * @since 2.0 <2015-4-15> SoChishun Refactoring function.
     */
    function check_verify($code, $id = 'captcha', $reset = true) {
        $verify = new \Think\Verify(array('reset' => $reset));
        return $verify->check($code, $id);
    }

    /**
     * 动态确认验证码是否正确
     * @param $v
     * @since 1.0 2014-9-27 by sutroon
     * @example
     * $('input[name="captcha"]').keyup(function(){
      var val=$(this).val();
      if(val.length>3){
      var url='{:U("Captcha/confirm","v=value")}';
      $.get(url.replace('value',val),function(data){
      $('.captcha-field label i').html(data?'[正确]':'[错误]');
      });
      }
      })
     */
    public function confirm($code, $id = 'captcha') {
        $this->ajaxReturn($this->check_verify($code, $id, false));
    }

}
